package cn.aitrox.ry.util;

import org.apache.commons.io.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class FileDownLoadUtil {

    private static Logger logger = LoggerFactory.getLogger(FileDownLoadUtil.class);


    public static void downLoad(String downloadUrl, String filePath, Integer connectTimeout, Integer socketTimeout) throws IOException {
        if (null == connectTimeout) {
            connectTimeout = 1000;
        }
        if (null == socketTimeout) {
            socketTimeout = 30000;
        }
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet(downloadUrl);
        // 建立连接时间 1秒， 数据传输时间 30秒
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();
        httpget.setConfig(requestConfig);
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        InputStream inputStream = entity.getContent();

        File file = new File(filePath);

        FileUtils.copyInputStreamToFile(inputStream, file);
    }

    public static void downLoadFromIS(InputStream inputStream, String filePath) throws IOException {
        File targetFile = new File(filePath);
        File parentFile = targetFile.getParentFile();
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(filePath);
            byte[] buf = new byte[2048];
            int len;
            while ((len = inputStream.read(buf)) != -1) {
                fos.write(buf, 0, len);
            }
            fos.flush();
        } finally {
            if (null != fos) {
                fos.close();
            }
            if (null != inputStream) {
                inputStream.close();
            }
        }
    }
}
